package main

import (
	"fmt"
	"sync"
)

// 使用互斥锁，解决并发问题

// 互斥锁
var lock sync.Mutex

// 阻塞
var block sync.WaitGroup

func main() {

	var num = 1

	block.Add(2)
	go increase(&num)

	go decrease(&num)

	block.Wait()
	fmt.Println(num)

}

// 加一
func increase(num *int) {
	for i := 0; i < 1000; i++ {
		lock.Lock()
		*num = *num + 1
		lock.Unlock()
	}
	defer block.Done()
}

// 减少
func decrease(num *int) {
	for i := 0; i < 1000; i++ {
		lock.Lock()
		*num = *num - 1
		lock.Unlock()
	}
	defer block.Done()
}
